#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <functional>
#include <vector> 

using namespace std;

using func_t = function<void()>;

int threadnum = 5;

class ThreadData
{
public:
    ThreadData(const string &name, const uint64_t &ctime, func_t f)
        :threadname(name)
        ,createtime(ctime)
        ,func(f)
    {}
public:
    string threadname;
    uint64_t createtime;
    func_t func;
};

void Print()
{
    cout << "我是大任务执行得一部分\n" << endl;
}

void *ThreadRountine(void *args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    while(1)
    {
        cout << "new thread" << ", thread name: " << td->threadname << ", createtime: " << td->createtime << endl;
        td->func();

        // if(td->threadname == "thread_4")
        // {
        //     cout << td->threadname << " 触发异常" << endl;
        //     int *p = nullptr;
        //     *p = 10;
        // }

        sleep(1);
    }
    
}

int main()
{
    vector<pthread_t> pthreads;
    for(size_t  i = 0; i < threadnum; i++)
    {
        char threadname[64];
        snprintf(threadname, sizeof(threadname), "%s_%lu", "thread", i+1);

        pthread_t tid;
        ThreadData *td = new ThreadData(threadname, (uint64_t)time(nullptr), Print);
        pthread_create(&tid, nullptr, ThreadRountine, td);
        pthreads.push_back(tid);
        sleep(1);
    }

    for(auto &tid : pthreads)
    {
        cout << tid << endl;
    }
    // pthread_t tid;

    // ThreadData *td = new ThreadData("thread_1", (uint64_t)time(nullptr), Print);

    // pthread_create(&tid, nullptr, ThreadRountine, td);
    
    while(1)
    {
        cout << "I am a main thread" << endl;
        sleep(1);
    }
    return 0;
}